﻿using System;
using System.Web.Mvc;
using System.Web.Security;
using TaskManager.Domain.BusinessObjects;
using TaskManager.Domain.Repositories;
using TaskManager.Web.Controls;
using TaskManager.Web.ViewModels.Account;

namespace TaskManager.Web.Controllers
{
    public class AccountController : Controller
    {
        private readonly IUserRepository _userRepository;
        private readonly IUnitOfWork _unitOfWork;
        private readonly TabContainer _tabContainer;

        public AccountController(IUserRepository userRepository, IUnitOfWork unitOfWork, TabContainer tabContainer)
        {
            _userRepository = userRepository;
            _unitOfWork = unitOfWork;
            _tabContainer = tabContainer;
        }

        //
        // GET: /Account/LogOn

        public ActionResult LogOn()
        {
            return View();
        }

        //
        // POST: /Account/LogOn

        [HttpPost]
        public ActionResult LogOn(LogOnModel model, string returnUrl)
        {
            if (ModelState.IsValid)
            {
                if (_userRepository.ValidateUser(model.UserName, model.Password))
                {
                    // Close all tabs that might be open in the previous session
                    _tabContainer.RemoveAll();

                    FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);
                    if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                        && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
                    {
                        return Redirect(returnUrl);
                    }
                    else
                    {
                        return RedirectToAction("MyTasks", "Task");
                    }
                }
                else
                {
                    ModelState.AddModelError("", "The user name or password provided is incorrect.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/LogOff

        public ActionResult LogOff()
        {
            FormsAuthentication.SignOut();

            return RedirectToAction("MyTasks", "Task");
        }

        //
        // GET: /Account/Register

        public ActionResult Register()
        {
            return View();
        }

        //
        // POST: /Account/Register

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            if (ModelState.IsValid)
            {
                Tuple<User, string> res = _userRepository.CreateUser(model.UserName, model.Password, model.Email,
                    () => _unitOfWork.Save());

                if(res.Item1 != null)
                {
                    FormsAuthentication.SetAuthCookie(model.UserName, false /* createPersistentCookie */);

                    TempData["info"] = string.Format(Resource.AccountController_Register_User, model.UserName);

                    return RedirectToAction("MyTasks", "Task");
                }
                else
                {
                    ModelState.AddModelError("", res.Item2);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePassword

        [Authorize]
        public ActionResult ChangePassword()
        {
            return View();
        }

        //
        // POST: /Account/ChangePassword

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            if (ModelState.IsValid)
            {
                bool res = _userRepository.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword);

                if (res)
                {
                    return RedirectToAction("ChangePasswordSuccess");
                }
                else
                {
                    ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }

        //
        // GET: /Account/ChangePasswordSuccess

        public ActionResult ChangePasswordSuccess()
        {
            return View();
        }
    }
}
